package com.demo.upload;

import java.io.*;

/**
 * @author gy
 * @date 2022/5/4
 */
public class StreamUtils {
    /**
     * 将输入流转化 成 byte[] 即可以把文件的内容读入到 byte[]
     * @param is
     * @return
     * @throws Exception
     */
    public static byte[] streamToByteArray(InputStream is) throws Exception{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        // 创建字节数组 缓冲区
        byte[] b = new byte[1024];
        int len;
        // 循环读取输入流
        while ((len = is.read(b))!= -1){
            bos.write(b,0,len);
        }
        byte[] array = bos.toByteArray();
        bos.close();
        return array;
    }


    /**
     * 将 输入流 转换成 字符串
     */
    public static String streamToString (InputStream is)throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        // 当读取到 null为表示结束
        while ((line = br.readLine())!= null){
            sb.append(line+"\r\n");
        }
        return sb.toString();
    }
}
